import json

def load_data_from_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return data
    except FileNotFoundError:
        print(f"错误: 文件 {file_path} 未找到。")
        return None
    except json.JSONDecodeError:
        print(f"错误: 文件 {file_path} 不是有效的 JSON 文件。")
        return None

def find_turning_point(data):
    stock_prices = {}
    all_dates = sorted({day["trandt"] for day in data}, reverse=True)

    # 获取最大日期
    max_date = all_dates[0]

    # 组织数据，以股票代码为键，存储每个日期的收盘价
    for day in data:
        date = day["trandt"]
        for stock in day["data"]["diff"]:
            stock_code = stock["f12"]
            close_price = stock["f2"]

            if stock_code not in stock_prices:
                stock_prices[stock_code] = []

            stock_prices[stock_code].append((date, close_price))

    # 找出最大日期的拐点数据
    turning_points = []
    for stock_code, prices in stock_prices.items():
        if len(prices) < 3:
            continue

        # 寻找最大日期的拐点
        for i in range(len(prices) - 1, 1, -1):
            if prices[i][0] == max_date and prices[i][1] > prices[i-1][1] and prices[i-1][1] < prices[i-2][1]:
                turning_points.append({
                    "stock_code": stock_code,
                    "date": prices[i][0],
                    "price": prices[i][1]
                })
                break

    return turning_points

def print_turning_points(turning_points):
    print("拐点数据:")
    for point in turning_points:
        print(f"股票代码: {point['stock_code']}")
        print(f"日期: {point['date']}")
        print(f"价格: {point['price']}")
        print()

# 主程序执行
file_path = '/Users/macbookair/workspace/pythonlearning/01test/tiantianjijin/all_processed_data.json'
data = load_data_from_file(file_path)

if data:
    turning_points = find_turning_point(data)
    print_turning_points(turning_points)
else:
    print("没有可处理的数据。")
